package xml;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.IOException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import palette.CanvasManager;
import palette.CanvasWindow;
import cuShapes.*;

public class XmlReader {
	JAXBContext ctx;
	Unmarshaller xmlReader;
	ShapeCollection shapeCollection;
	
	// specify where the XML schema is located
    final File dir = new File("generated" + File.separator + "schema");
    InputStream is;
    
    public XmlReader() {
    	initialize();
    }
    
    private void initialize() {
		try {
			ctx = JAXBContext.newInstance(ShapeCollection.class);
			xmlReader = ctx.createUnmarshaller();
			// generate an XML schema from the annotated object model; create it
	        // in the dir specified earlier under the default name, schema1.xsd
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
    
    public void read(String xmlFileName) {
    	try {
	    	// specify a name for the generated XML instance document
    		is = new FileInputStream(new File(xmlFileName));
	        shapeCollection = (ShapeCollection) xmlReader.unmarshal(is);
        } catch (JAXBException jbe) {
            jbe.printStackTrace();
	    } catch (IOException e) {
	    	System.out.println("File not found");
	    	e.printStackTrace();
	    }
	    
	    for(PQShape e : shapeCollection.getShapeList()) {
	    	((CanvasWindow)CanvasManager.getInst().getSelectedFrame()).getCanvas().getShapeList().add(e);	
	    }
	    for(PQShape e : shapeCollection.getArrowList()) {
	    	((CanvasWindow)CanvasManager.getInst().getSelectedFrame()).getCanvas().getArrowList().add((Arrow)e);
	    }
    }
}
